﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Smart.Service
{
    public class XmlServiceResult : XmlServiceRequest, IServiceResult
    {
        public XmlServiceResult()
        {
            Message = new MessageInfo();
            Root = new System.Xml.Linq.XElement("result");
        }

        public IMessageInfo Message { get; protected set; }

        public override string ToXmlString()
        {
            XElement msg = new XElement("message", Message.ToString());
            msg.SetAttributeValue("status", Message.Status);
            Root.Add(msg); ;
            return Root.ToString();
        }

        public static XmlServiceResult FromXmlString(string result)
        {
            XElement xe = XElement.Parse(result);
            var res = new XmlServiceResult();
            foreach (var x in xe.Elements())
            {
                if (x.Name.ToString().Equals("message"))
                {
                    res.Message.Status = int.Parse(x.Attribute("status").Value);
                    res.Message.Add(x.Value);
                    continue;
                }

                res[x.Name.ToString()] = x.Value.ToString();
            }

            return res;
        }
    }
}
